package org.warehouse.controller;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.warehouse.dao.engine.DaoException;
import org.warehouse.dao.engine.DbExecutor;
import org.warehouse.entity.Product;
import org.warehouse.service.IService;
import org.warehouse.service.Service;
import org.warehouse.util.Sort;

/**
 * The controller prepare data for view
 */
@WebServlet("/")
public class Controller extends HttpServlet {
	public static final long serialVersionUID = 4634562565398979050L;

	public IService service;
	
	public DbExecutor dbExecutor;

	@Override
	public void init() throws ServletException {
		super.init();
		service = Service.getInstance();
		dbExecutor = DbExecutor.getInstance();
	}
	
	@Override
	public void destroy() {
	    super.destroy();
	    
	    // Close a connection before servlet will be unloaded
	    dbExecutor.closeConnection();
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// TODO should think how to escape calling several times
			prepareSession(request);

			if (redirectIfNecessary(request, response)) {
				return;
			}
			
			fillRequestData(request);
			
			request.getRequestDispatcher("WEB-INF/main.jsp").forward(request, response);
		} catch (DaoException e) {
			throw new ServletException("Retrieving groups failed!", e);
		}

	}
	
	/**
	 * TODO Bad implementation of removing GET parameters from request
	 * @param request
	 * @return returns <code>true</code> if a redirect has been sent, else -<code>false</code>
	 * @throws IOException 
	 */
	private boolean redirectIfNecessary(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession(false);

		// Redirect after sorting for preventing resort after refresh of screen
		if (request.getParameter(Keys.LAST_SORT_COLUMN_NAME_KEY) != null) {
			int groupId = (Integer) session.getAttribute(Keys.CURRENT_GROUP_KEY);
			if (groupId > 0) {
				response.sendRedirect(MessageFormat.format("/warehouse/products?{0}={1}", Keys.CURRENT_GROUP_KEY, groupId));
			} else {
				response.sendRedirect("/warehouse/");
			}
			return true;
		}
		
		// Redirect after page navigation for preventing auto navigation after refresh of screen		
		if (request.getParameter(Keys.PAGE_NAVIGATE_KEY) != null) {
			int currentPage = (Integer) session.getAttribute(Keys.CURRENT_PAGE_KEY);
			response.sendRedirect(MessageFormat.format("/warehouse/products?{0}={1}", Keys.CURRENT_PAGE_KEY, currentPage));
			return true;
		}
		
		return false;
	}
	
	/**
	 * Puts data to request attributes for using by view's
	 * 
	 * @param request
	 */
	private void fillRequestData(HttpServletRequest request) {
		// Add groups in to request
		request.setAttribute(Keys.GROUPS_KEY, service.getGroups());

		HttpSession session = request.getSession(false);
		
		int groupId = (Integer) session.getAttribute(Keys.CURRENT_GROUP_KEY);
		
		// Add count of pages in to request
		request.setAttribute(Keys.COUNT_OF_PAGES_KEY, service.getCountOfPages(groupId));

		// Add necessary products in to request
		int currentPage = (Integer) session.getAttribute(Keys.CURRENT_PAGE_KEY);
		Sort sortByName = Sort.valueOf((String) session.getAttribute(Keys.CURRENT_NAME_SORT_KEY));
		Sort sortByPrice = Sort.valueOf((String) session.getAttribute(Keys.CURRENT_PRICE_SORT_KEY));
		String lastSortColumnName = (String) session.getAttribute(Keys.LAST_SORT_COLUMN_NAME_KEY);
		List<Product> products = service.getProducts(groupId, currentPage, sortByName, sortByPrice, lastSortColumnName);
		request.setAttribute(Keys.PRODUCTS_KEY, products);
	}

	/**
	 * Creates session if it's needed and stores default values in them
	 * 
	 * @param session
	 */
	private void prepareSession(HttpServletRequest request) {
		// Create if needed
		HttpSession session = request.getSession(true);
		
		// Set selected group id
		if (session.getAttribute(Keys.CURRENT_GROUP_KEY) == null) {
			session.setAttribute(Keys.CURRENT_GROUP_KEY, -1);
		}

		// Set default number of page
		if (session.getAttribute(Keys.CURRENT_PAGE_KEY) == null) {
			session.setAttribute(Keys.CURRENT_PAGE_KEY, 0);
		}
		
		// Set start number of a page list
		if (session.getAttribute(Keys.PAGE_START_INDEX_OF_KEY) == null) {
			session.setAttribute(Keys.PAGE_START_INDEX_OF_KEY, 1);
		}

		// Set default sort by name
		if (session.getAttribute(Keys.CURRENT_NAME_SORT_KEY) == null) {
			session.setAttribute(Keys.CURRENT_NAME_SORT_KEY, Sort.ASC.name());
		}

		// Set default sort by price
		if (session.getAttribute(Keys.CURRENT_PRICE_SORT_KEY) == null) {
			session.setAttribute(Keys.CURRENT_PRICE_SORT_KEY, Sort.ASC.name());
		}

		// Set default sort by price
		if (session.getAttribute(Keys.LAST_SORT_COLUMN_NAME_KEY) == null) {
			session.setAttribute(Keys.LAST_SORT_COLUMN_NAME_KEY, "PRODUCT_NAME");
		}
	}
}
